package com.lijie.ljblog.schedule;

import com.lijie.ljblog.model.Mail;
import com.lijie.ljblog.service.LjpageWebsitehotService;
import com.lijie.ljblog.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 定时任务，每2个小时 获取一次
 * @author lj
 * @date 2023/5/16 19:48
 * @description
 */
@Component
@Slf4j
public class HotNewsSchedule {

    @Resource
    LjpageWebsitehotService ljpageWebsitehotService;
    @Resource
    MailService mailService;

    @Value("${lijieEmail}")
    String ljEmail;

    public static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式
    /**
     * 每两小时同步一次
     *
     * 2023-05-16 23:00:00
     * 2023-05-17 01:00:00
     * 2023-05-17 03:00:00
     * 2023-05-17 05:00:00
     * 2023-05-17 07:00:00
     * 2023-05-17 09:00:00
     * 2023-05-17 11:00:00
     * 2023-05-17 13:00:00
     * 2023-05-17 15:00:00
     * 2023-05-17 17:00:00
     */
    @Scheduled(cron="0 0 1/2 * * ?")
    public void execute(){
        long begin = System.currentTimeMillis();
        log.info(df.format(new Date())+",开始获取热榜数据");
        Integer integer;
        try{
             integer = ljpageWebsitehotService.hotDailyUpdate();
        }catch (Exception e){
            String errorMessage="热榜数据更新失败，错误信息："+e.getMessage();
            log.info(errorMessage);
            //发邮件
            Mail mail=new Mail();
            mail.setEmail(ljEmail);//留言的收件人只会是我自己
            mail.setContent(errorMessage);
            mail.setTitle("ljPage 热榜数据更新失败");
            mailService.sendTextMail(mail);
            return;
        }
        long end = System.currentTimeMillis();
        log.info("热榜数据获取成功，更新了"+integer+"条数据，用时"+(end-begin)+"毫秒");
    }
}
